<template>
  <div class="face_landmark_detection">
    <div class="option">
      <div>
        <label>更换图片：</label>
        <input
          type="file"
          accept="image/png, image/jpeg"
          @change="fnChange($event)"
        />
      </div>
      <div>
        <label>边框Or面部轮廓：</label>
        <input type="checkbox" v-model="withBoxes" />
      </div>
      <div>
        <label>选择算法模型：</label>
        <label>
          ssdMobilenetv1
          <input type="radio" v-model="nets" value="ssdMobilenetv1" />
        </label>
        <label>
          tinyFaceDetector
          <input type="radio" v-model="nets" value="tinyFaceDetector" />
        </label>
        <label>
          mtcnn
          <input type="radio" v-model="nets" value="mtcnn" />
        </label>
      </div>
    </div>
    <div class="see">
      <img src="./2.png" style="width: 600px; height: auto" id="myImg" />
      <!--      <canvas id="myCanvas" width="400" height="400"/>-->
      <div class="box" :style="{ width, height, left, top }">
        <div class="score" v-if="score > 0">{{ toFixedTwo(score) }}</div>
      </div>
    </div>
  </div>
</template>

<script>
import * as faceapi from 'face-api.js'
export default {
  name: 'FaceLandmarkDetection',
  data() {
    return {
      nets: 'ssdMobilenetv1', // 模型
      options: null, // 模型参数
      withBoxes: true, // 边框or轮廓
      imgEl: null,
      canvasEl: null,
      left: 0,
      top: 0,
      width: 0,
      height: 0,
      score: 0,
    }
  },
  watch: {
    nets(val) {
      this.nets = val
      this.fnInit().then(() => this.fnRun())
    },
    withBoxes(val) {
      this.withBoxes = val
      this.fnRun()
    },
  },
  mounted() {
    this.imgEl = document.getElementById('myImg')
    this.canvasEl = document.getElementById('myCanvas')
    this.$nextTick(() => {
      // 节点属性化
      console.log(this.imgEl, this.canvasEl)
      this.fnInit().then(() => this.fnRun())
    })
  },
  methods: {
    toFixedTwo(num) {
      if (typeof num === 'string') {
        return num.slice(0, 5)
      } else if (typeof num === 'number') {
        num = num.toString() // 转换为字符串格式的两位小数
        return num.slice(0, 5)
      }
      return 0
    },
    // 初始化模型加载
    async fnInit() {
      await faceapi.nets[this.nets].loadFromUri('/models')
      await faceapi.loadFaceLandmarkModel('/models')
      // 根据模型参数识别调整结果
      switch (this.nets) {
        case 'ssdMobilenetv1':
          this.options = new faceapi.SsdMobilenetv1Options({
            minConfidence: 0.5, // 0.1 ~ 0.9
          })
          break
        case 'tinyFaceDetector':
          this.options = new faceapi.TinyFaceDetectorOptions({
            inputSize: 512, // 160 224 320 416 512 608
            scoreThreshold: 0.5, // 0.1 ~ 0.9
          })
          break
        case 'mtcnn':
          this.options = new faceapi.MtcnnOptions({
            minFaceSize: 20, // 1 - 50
            scaleFactor: 0.709, // 0.1 ~ 0.9
          })
          break
      }
    },
    // 执行识别绘制
    async fnRun() {
      if (this.imgEl) {
        const results = await faceapi
          .detectAllFaces(this.imgEl, this.options)
          .withFaceLandmarks()
        /*              faceapi.matchDimensions(this.canvasEl, this.imgEl);*/
        const resizedResults = faceapi.resizeResults(results, this.imgEl)
        if (resizedResults.length) {
          let {
            _width = 0,
            _height = 0,
            _x = 0,
            _y = 0,
          } = resizedResults[0]?.detection._box
          let { _score } = resizedResults[0]?.detection
          this.width = _width + 'px'
          this.height = _height + 'px'
          this.left = _x + 'px'
          this.top = _y + 'px'
          this.score = Number(_score)
        }
        console.log(resizedResults)
      }
    },
    changeFileIntoBase64(file) {
      return new Promise((resolve, reject) => {
        const fr = new FileReader()
        fr.readAsDataURL(file)
        fr.onload = (result) => {
          const base64Str = result.currentTarget.result
          resolve(base64Str)
        }
      })
    },
    // 更换图片
    async fnChange(e) {
      if (!e.target.files.length) return
      // 将文件显示为图像并识别
      let data = await this.changeFileIntoBase64(e.target.files[0])
      this.imgEl.src = data
      this.fnRun()
      /*      faceapi.bufferToImage(data).then(async (img) => {
        this.imgEl.src = img.src;
/!*        this.canvasEl
            .getContext("2d")
            .clearRect(0, 0, this.canvasEl.width, this.canvasEl.height);*!/
        this.fnRun();
      });*/
    },
  },
}
</script>

<style scoped>
.see {
  position: relative;
}
.face_landmark_detection {
  width: 100%;
  height: 150px;
}
.see img {
  max-width: 600px;
  max-height: 400px;
}
.see canvas {
  position: absolute;
  top: 0;
  left: 0;
}
.option {
  padding-bottom: 20px;
}
.option div {
  padding: 10px;
  border-bottom: 2px #42b983 solid;
}
.option div label {
  margin-right: 20px;
}
.myImg {
  width: 400px;
  height: 600px;
}
.box {
  position: absolute;
  border: 2px solid #42b983;
}
.score {
  position: absolute;
  right: 0;
  top: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
  background-color: #42b983;
  font-size: 14px;
  padding: 5px;
  box-sizing: border-box;
}
</style>
